package com.ldu.exam.service;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ldu.exam.assistant.BeanAssistant;
import com.ldu.exam.dao.ClaRepository;
import com.ldu.exam.dao.NoticeRepository;
import com.ldu.exam.model.ClaModel;
import com.ldu.exam.model.ClaModelForm;

@Service
public class ClaService {
	@Autowired ClaRepository repository;
	@Autowired NoticeRepository noticeRepository;
	
	public List<ClaModel> findAllNoPage()
	{
		return this.repository.findAll();
	}
	public Page<ClaModel> findAll(Pageable page)
	{
		return this.repository.findAll(page);
	}
	public Page<ClaModel> findByName(String name,int page,int size)
	{
		return StringUtils.isEmpty(name) ?
				this.repository.findAll(PageRequest.of(page, size)) :
				this.repository.findByClaNameContaining(name, PageRequest.of(page, size)) ;
	}
	public Object save(ClaModelForm model) 
	{
//		NoticeModel noticeModel = new NoticeModel();
//		noticeModel.setAccountId(accountId);
		return this.repository.save(this.handle(model));
	}
	public Object update(String id , ClaModel model)
	{
		model.setId(null);
		model.setCreated(null);
		ClaModel origin = this.repository.findById(id).orElse(null);
		String [] nullPropertyNameStrings = BeanAssistant.getNullPropertyNames(model);
		BeanUtils.copyProperties(model, origin, nullPropertyNameStrings);
		return this.repository.save(origin);
	}
	public Object isExit(String name)
	{
		List<ClaModel> list = this.repository.findByClaName(name);
		if(list.size()>0) {
			return false;
		}else {
			return true;
		}
	}
	public Object del(String id) {
		ClaModel model = new ClaModel();
		model.setId(id);
		this.repository.delete(model);
		return null;
	}
	public ClaModel handle(ClaModelForm model)
	{
		ClaModel cm = new ClaModel();
		if(!StringUtils.isEmpty(model.getId()))
			cm.setId(model.getId());
		if(!StringUtils.isEmpty(model.getClaName()))
			cm.setClaName(model.getClaName());
		if(!StringUtils.isEmpty(model.getStudentsNum()))
			cm.setStudentsNum(model.getStudentsNum());
		if(!StringUtils.isEmpty(model.getState()))
			cm.setState(model.getState());
		if(!StringUtils.isEmpty(model.getSummary()))
			cm.setSummary(model.getSummary());
		if(!StringUtils.isEmpty(model.getAccount()))
			cm.setAccount(model.getAccount());
		if(!StringUtils.isEmpty(model.getExam()))
			cm.setExam(model.getExam());
		return cm;
	}
}
